/**
 * 
 */
package org.vsg.stock.basic.service.handler;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.vsg.common.biz.exception.ServiceException;
import org.vsg.stock.basic.domain.VolCharacterKlineDaily;
import org.vsg.stock.basic.domain.VolCharacterKlineDailyPK;
import org.vsg.stock.basic.domain.VolCharacterOfFigurePrepared;
import org.vsg.stock.basic.domain.VolFigureKlineDaily;
import org.vsg.stock.basic.persistence.VolCharacterKlineDailyDao;
import org.vsg.stock.basic.persistence.VolFigureKlineDailyDao;
import org.vsg.stock.bulk.io.PostgreSQLDataImport;
import org.vsg.stock.core.domain.StockDailyKLine;

/**
 * @author Bill Vison
 *
 */
public class VolCharacterKlineDailyHandlerManager {

	/**
	 * set the logger for developer code , do not use System.print(ln) to out print message.
	 */
	private static final Logger logger = LoggerFactory.getLogger(VolCharacterKlineDailyHandlerManager.class);
	
	@Resource
	private VolFigureKlineDailyDao volFigureKlineDailyDao;
	
	
	@Resource
	private VolCharacterKlineDailyDao volCharacterKlineDailyDao;
	
	@Resource
	private VolCharacterKlineDailyProcessor  volCharacterKlineDailyProcessor;

	
	static private DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	
	@Autowired
	private PostgreSQLDataImport postgreSQLDataImport;
	
	
	public void process(List<StockDailyKLine> stkDailyKLineList , Date startDate , Date endDate ) {
		// --- return out when the size is zero ---
		if ( stkDailyKLineList.size() == 0) {
			return;
		}
		
		List<Date> existDateVec = new Vector<Date>();

		for (StockDailyKLine chkDailyKLine : stkDailyKLineList ) {
			existDateVec.add( chkDailyKLine.getId().getDate() );
		}
	
		String stockCode = stkDailyKLineList.get(0).getId().getStockCode();
		
		// --- get the exist key ---
		List<VolCharacterKlineDaily> volCharaDailyList = volCharacterKlineDailyDao.findVolCharacKlineDailyInCycleByStck(stockCode, startDate, endDate);

		
		/*
		 * execute processor handle 
		 */
		volCharacterKlineDailyProcessor.setExistedVolCharacterKlineDaily( volCharaDailyList );
		
		List<VolCharacterKlineDaily> characterDailVec = volCharacterKlineDailyProcessor.processDailyData(stkDailyKLineList, stockCode);
		
		// ---- check the handle list ---
		if ( characterDailVec != null && characterDailVec.size() > 0) {
			persistenceList(characterDailVec);
		}
		
		// --- last update
		persistenceLast();

		
	}
	
	private List<VolCharacterKlineDaily> resultProxy = new Vector<VolCharacterKlineDaily>();
	
	
	private void persistenceList(List<VolCharacterKlineDaily> result) {
		resultProxy.addAll( result );
		if ( resultProxy.size() > 4000) {
			saveToDb(resultProxy);
			resultProxy.clear();
		}
	}
	
	private void persistenceLast() {

		if ( resultProxy.size() > 0) {
			saveToDb(resultProxy);
			resultProxy.clear();
		}
	}	
	
	private void saveToDb(List<VolCharacterKlineDaily> result ) {
		
		StringBuffer dataOutput = new StringBuffer();
		VolCharacterKlineDailyPK pk = null;
		for (VolCharacterKlineDaily daily : result) {
			pk = daily.getId();
			dataOutput.append(pk.getStockCode()).append(",");
			dataOutput.append(df.format( pk.getStockStartDate() )).append(",");
			dataOutput.append(	daily.getLevelGolden() ).append(",");
			dataOutput.append(
					df.format( daily.getGoldenDate() ) ).append(",");
			if ( daily.getStockEndDate() != null ) {
				dataOutput.append(df.format( daily.getStockEndDate() ));
			}

			dataOutput.append("\n");
			
		}


		
		// --- import new data ----

		InputStream is  = null;
		
		postgreSQLDataImport.connect();
		
		String[] fields = {
				"stock_code" ,
				"stock_date_start",
				"level_golden",
				"golden_date",
				"stock_date_end"
		};
		
		try {

			is = IOUtils.toInputStream(dataOutput.toString());
			
			// --- import data ----
			postgreSQLDataImport.importData("vol_character_kline_daily", is, fields);
			
			logger.info("import stock vol character kline daily data ok!");
			
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		postgreSQLDataImport.disconnect();

	}
	

}
